//
//  AyHomeViewController.m
//  weibo
//
//  Created by alvis mac on 8/1/15.
//  Copyright (c) 2015 alvis. All rights reserved.
//

#import "AyHomeViewController.h"
#import "UIBarButtonItemExtend.h"
#import "AyDefine.h"
#import "AyTitleButton.h"
#import "UIImageExtend.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "MJExtension.h"
#import "AyStatusFrame.h"
#import "AyAccountTool.h"
#import "AyStatusCell.h"
#import "MJRefresh.h"
#import "AyUserInfoParam.h"
#import "AyUserInfoResult.h"
#import "AyUserTool.h"
#import "AyHomeStatusesParame.h"
#import "AyHomeStatusesResult.h"
#import "AyStatusTool.h"
#import "StatusDetaiViewController.h"


@interface AyHomeViewController ()<MJRefreshBaseViewDelegate>
@property (nonatomic, strong)  NSMutableArray * statusFrames;
@property (nonatomic, weak)  AyTitleButton * titleButton;
@property (nonatomic, weak)  MJRefreshHeaderView * header;
@property (nonatomic, weak)  MJRefreshFooterView * footer;
@end


@implementation AyHomeViewController

- (NSArray *)statusFrames{
    if (_statusFrames == nil) {
        _statusFrames=[NSMutableArray array];
    }
    return _statusFrames;
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
    [self setupRefreshView];
    [self setupNavBar];
    [self setupUserData];
}


- (void) setupUserData{
    AyUserInfoParam *param=[AyUserInfoParam param];
    param.uid = @([AyAccountTool account].uid);
    [AyUserTool userInfoWithParam:param success:^(AyUserInfoResult *result) {
        [self.titleButton setTitle:result.name forState:UIControlStateNormal];
        AyAccount *account = [AyAccountTool account];
        account.name = result.name;
        [AyAccountTool saveAccount:account];
    } failure:^(NSError *error) {
        
    }];
}




- (void)setupNavBar
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"navigationbar_friendsearch" highIcon:@"navigationbar_friendsearch_highlighted" target:self action:@selector(findFriend)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithIcon:@"navigationbar_pop" highIcon:@"navigationbar_pop_highlighted" target:self action:@selector(pop)];
    
    
    AyTitleButton *titleButton = [AyTitleButton titleButton];
    [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
     titleButton.frame = CGRectMake(0, 0, 0, 40);
    if ([AyAccountTool account].name) {
        [titleButton setTitle:[AyAccountTool account].name forState:UIControlStateNormal];
    }
    else{
        [titleButton setTitle:@"首页" forState:UIControlStateNormal];
    }
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleButton;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = AyColor(226, 226, 226);
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, AyStatusTableBorder, 0);
}



- (void)setupRefreshView
{
    MJRefreshHeaderView *header=[MJRefreshHeaderView header];
    header.scrollView=self.tableView;
    header.delegate=self;
    [header beginRefreshing];
    self.header=header;
    
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    footer.delegate = self;
    self.footer = footer;
}


-(void)dealloc{
    [self.header free];
    [self.footer free];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView{
    if ([refreshView isKindOfClass:[MJRefreshFooterView class]]) {
        [self loadMoreData];
    } else { // 下拉刷新
        [self loadNewData];
    }
}

- (void) loadMoreData{
    
    AyHomeStatusesParame *param=[AyHomeStatusesParame param];
    if (self.statusFrames.count) {
         AyStatusFrame *statusFrame=[self.statusFrames lastObject];
         param.max_id=@([statusFrame.status.idstr longLongValue]-1);
    }
    
    [AyStatusTool homeStatusesWithParam:param success:^(AyHomeStatusesResult *result) {
        NSMutableArray *statusFramArray = [NSMutableArray array];
        for(AyStatus *status in result.statuses){
            AyStatusFrame *sframe=[[AyStatusFrame alloc] init];
            sframe.status=status;
            [statusFramArray addObject:sframe];
        }
        [self.statusFrames addObjectsFromArray:statusFramArray];
        [self.tableView reloadData];
        [self.footer endRefreshing];
    } failure:^(NSError *error) {
        [self.footer endRefreshing];
    }];
}

- (void) loadNewData{
    self.tabBarItem.badgeValue=nil;
    
    AyHomeStatusesParame *param=[AyHomeStatusesParame param];
    if (self.statusFrames.count) {
        AyStatusFrame *statusFrame=[self.statusFrames firstObject];
        param.since_id=@([statusFrame.status.idstr longLongValue]);
    }
    
    [AyStatusTool homeStatusesWithParam:param success:^(AyHomeStatusesResult *result) {
        NSMutableArray *statusFramArray=[NSMutableArray array];
        for(AyStatus *status in result.statuses){
            AyStatusFrame *sframe=[[AyStatusFrame alloc] init];
            sframe.status=status;
            [statusFramArray addObject:sframe];
        }
        
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObjectsFromArray:statusFramArray];
        [tempArray addObjectsFromArray:self.statusFrames];
        self.statusFrames = tempArray;
        [self.tableView reloadData];
        [self.header endRefreshing];
        [self showNewStatusCount:statusFramArray.count];
        
    } failure:^(NSError *error) {
         [self.header endRefreshing];
    }];
    
}

- (void) showNewStatusCount:(int) count{
    UIButton *btn=[[UIButton alloc] init];
    [self.navigationController.view insertSubview:btn belowSubview:self.navigationController.navigationBar];
    btn.userInteractionEnabled = NO;
    [btn setBackgroundImage:[UIImage resizedImageWithName:@"timeline_new_status_background"] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    if (count) {
        NSString *title = [NSString stringWithFormat:@"共有%d条新的微博", count];
        [btn setTitle:title forState:UIControlStateNormal];
    } else {
        [btn setTitle:@"没有新的微博数据" forState:UIControlStateNormal];
    }
    
    CGFloat btnH=30;
    CGFloat btnY=64-btnH;
    CGFloat btnX=2;
    CGFloat btnW=self.view.frame.size.width-2 * btnX;
    btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
    [UIView animateWithDuration:0.7 animations:^{
        btn.transform=CGAffineTransformMakeTranslation(0, btnH+2);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.7 delay:1.0 options:UIViewAnimationOptionCurveLinear animations:^{
            btn.transform=CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [btn removeFromSuperview];
        }];
    }];

}


- (void) refresh{
    if ([self.tabBarItem.badgeValue intValue]!=0) {
        [self.header beginRefreshing];
    }
};


- (void)titleClick:(AyTitleButton *)titleButton
{
    if (titleButton.tag== 999) {
        [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
        titleButton.tag=-1;
    } else {
        [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
        titleButton.tag= 999;
    }
}

- (void)findFriend
{
   AyLog(@"findFriend");
}
                                           
 - (void)pop
{
    AyLog(@"pop");
}
                                           
                                           
                                           


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statusFrames.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AyStatusCell *cell=[AyStatusCell cellWithTableView:tableView];
    cell.statusFrame=self.statusFrames[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AyStatusFrame *statusFrame = self.statusFrames[indexPath.row];
    return statusFrame.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AyStatusFrame *f = _statusFrames[indexPath.row];
    StatusDetaiViewController *detail = [[StatusDetaiViewController alloc] init];
    detail.status = f.status;
    [self.navigationController pushViewController:detail animated:YES];
}



@end
